<template>
  <div class="user-page">
    <div class="user-info" v-if="user">
      <img :src="user.avatar || defaultAvatar" class="avatar" />
      <div class="info">
        <h2>{{ user.nickname || user.username }}</h2>
        <p>{{ user.bio }}</p>
      </div>
    </div>
    <div class="user-posts">
      <h3>TA的作品</h3>
      <div class="posts-list">
        <div v-for="post in posts" :key="post._id" class="post-card" @click="goDetail(post._id)">
          <img :src="post.cover" class="post-cover" />
          <div class="post-title">{{ post.title }}</div>
        </div>
      </div>
      <div v-if="loading" class="loading">加载中...</div>
      <div v-if="!hasMore && posts.length > 0" class="no-more">没有更多了</div>
    </div>
  </div>
</template>

<script setup>
const defaultAvatar = '/default-avatar.png'
import api from '@/utils/api'
import { onMounted, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'

const route = useRoute()
const router = useRouter()
const userId = route.params.userId
const user = ref(null)
const posts = ref([])
const page = ref(1)
const pageSize = 30
const hasMore = ref(true)
const loading = ref(false)

const fetchUser = async () => {
  const res = await api.user.getProfile(userId)
  if (res && res.data) user.value = res.data
}
const fetchPosts = async () => {
  if (!hasMore.value || loading.value) return
  loading.value = true
  const res = await api.user.getPosts(userId, page.value, pageSize)
  if (res && res.data && res.data.length) {
    posts.value.push(...res.data)
    if (res.data.length < pageSize) hasMore.value = false
    else page.value++
  } else {
    hasMore.value = false
  }
  loading.value = false
}
const goDetail = id => router.push(`/detail?id=${id}`)

const handleScroll = () => {
  if (!hasMore.value || loading.value) return
  const scrollBottom = window.innerHeight + window.scrollY >= document.body.offsetHeight - 10
  if (scrollBottom) fetchPosts()
}

onMounted(() => {
  fetchUser()
  fetchPosts()
  window.addEventListener('scroll', handleScroll)
})
</script>

<style scoped>
.user-page {
  max-width: 900px;
  margin: 0 auto;
  padding: 24px;
}

.user-info {
  display: flex;
  align-items: center;
  margin-bottom: 32px;
}

.avatar {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  object-fit: cover;
  margin-right: 24px;
}

.info h2 {
  margin: 0 0 8px 0;
}

.user-posts {
  margin-top: 24px;
}

.posts-list {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
}

.post-card {
  width: 180px;
  cursor: pointer;
  border: 1px solid #eee;
  border-radius: 8px;
  overflow: hidden;
  background: #fff;
  transition: box-shadow .2s;
}

.post-card:hover {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.post-cover {
  width: 100%;
  height: 120px;
  object-fit: cover;
}

.post-title {
  padding: 8px;
  font-size: 16px;
  font-weight: 500;
}

.loading,
.no-more {
  text-align: center;
  color: #888;
  margin: 16px 0;
}
</style>
